package com.cqh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqh.common.R;
import com.cqh.entity.Category;
import com.cqh.service.CategotyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    private  CategotyService categotyService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        categotyService.save(category);
        log.info("category{}",category);
        return R.success("新增分类成功");
    }
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
       Page<Category> pageinfo=new Page<>(page,pageSize);
       LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper();
       lambdaQueryWrapper.orderByAsc(Category::getSort);
       pageinfo=categotyService.page(pageinfo,lambdaQueryWrapper);
       return R.success(pageinfo);
    }

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public R<String> delete(  Long id){

        categotyService.remove(id);
        return  R.success("删除成功");

    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){

        categotyService.updateById(category);


        return R.success("修改分类成功");
    }

    @GetMapping("/list")
    public R<List>  list( Category category){
      LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper<>();
      lambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
      lambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
      List<Category> categoryList=categotyService.list(lambdaQueryWrapper);
        return  R.success(categoryList);
    }

}
